package com.example.SearchAmbitus.view;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.*;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.*;
import com.baidu.mapapi.model.LatLng;
import com.example.SearchAmbitus.R;
import model.LocationDataRequester;
import org.json.JSONException;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Bxh on 2014/11/26.
 */
public class POIListActivity extends Activity {

    private Button btn_poilist_goBack;
    private Button btn_poilist_chang;
    private TextView textView_poilist_title;

    private LinearLayout layout_poilist_ListView;
    private ListView listView_poiList;
    private List<Map<String, Object>> list;
    private Button btn_poilist_morn;

    private RelativeLayout layout_poilist_Map;
    private Button btn_poilist_pre;
    private Button btn_poilist_next;
    private Button btn_poilist_reset;

    private LinearLayout LinearLayout_poilist;
    private TextView TextView_m;

    //所需的参数
    private double lat;//纬度
    private double lon;//经度
    private String name;//关键字
    private int range = 3000;//搜索半径
    boolean isFirstLoc = true;// 是否首次定位
    private int flag = 0;

    private MapView mMapView;
    private BaiduMap mBaiduMap;
    private String title;

    private  Map<String, Marker> markerMap = new HashMap<String, Marker>();

    private int abc = 10;
    private int m = 1;
    // 定位相关
    LocationClient mLocClient;
    public MyLocationListenner myListener = new MyLocationListenner();

    public POIListActivity() {
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        SDKInitializer.initialize(getApplicationContext());
        setContentView(R.layout.activity_poilist);

        textView_poilist_title = (TextView) findViewById(R.id.textView_poilist_title);
        //选择范围
        LinearLayout_poilist = (LinearLayout) findViewById(R.id.LinearLayout_poilist);
        TextView_m = (TextView) findViewById(R.id.TextView_m);
        LinearLayout_poilist.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog();
            }
        });
        //列表模式
        btn_poilist_goBack = (Button) findViewById(R.id.btn_poilist_goBack);
        btn_poilist_chang = (Button) findViewById(R.id.btn_poilist_chang);
        layout_poilist_ListView = (LinearLayout) findViewById(R.id.layout_poilist_ListView);
        listView_poiList = (ListView) findViewById(R.id.listView_poiList);
        btn_poilist_morn = (Button) findViewById(R.id.btn_poilist_morn);

        //地图模式
        layout_poilist_Map = (RelativeLayout) findViewById(R.id.layout_poilist_Map);
        btn_poilist_pre = (Button) findViewById(R.id.btn_poilist_pre);
        btn_poilist_next = (Button) findViewById(R.id.btn_poilist_next);
        btn_poilist_reset = (Button) findViewById(R.id.btn_poilist_reset);


//切换界面显示  《地图。列表》

        layout_poilist_Map.setVisibility(View.GONE);


        btn_poilist_chang.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (flag == 0) {
                    Drawable drawable = getResources().getDrawable(R.drawable.ic_action_list);
                    layout_poilist_ListView.setVisibility(View.GONE);
                    layout_poilist_Map.setVisibility(View.VISIBLE);
                    btn_poilist_chang.setBackground(drawable);
                    flag = 1;

                } else if (flag == 1) {
                    Drawable drawable1 = getResources().getDrawable(R.drawable.ic_action_map);
                    layout_poilist_Map.setVisibility(View.GONE);
                    layout_poilist_ListView.setVisibility(View.VISIBLE);
                    btn_poilist_chang.setBackground(drawable1);
                    flag = 0;
                }

            }
        });


        //跳转获取数据
        Intent intent = getIntent();
        lat = intent.getDoubleExtra("lat", 38.11111);
        lon = intent.getDoubleExtra("lon", 108.11111);
        name = intent.getStringExtra("name");
        Log.d("lat", lat + "");
        textView_poilist_title.setText(name);

        //获取POI list数据

        getLocationData();
        //更多数据
        btn_poilist_morn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                abc += 5;
                getLocationData();
            }
        });


        btn_poilist_goBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        btn_poilist_next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                m += 1;
                getNextMarker();


            }
        });
        btn_poilist_pre.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                m -= 1;
                getNextMarker();

            }
        });
        //地位地图显示
        // 地图初始化
        mMapView = (MapView) findViewById(R.id.bMapView);
        mBaiduMap = mMapView.getMap();
        //设置缩放等级
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(14.0f);
        mBaiduMap.setMapStatus(msu);
        //开启交通图
//        mBaiduMap.setTrafficEnabled(true);
        // 开启定位图层
        mBaiduMap.setMyLocationEnabled(true);
        // 定位初始化
        mLocClient = new LocationClient(this);
        mLocClient.registerLocationListener(myListener);
        LocationClientOption option = new LocationClientOption();


        //POI点的点击事件
        mBaiduMap.setOnMarkerClickListener(new BaiduMap.OnMarkerClickListener() {
            @Override
            public boolean onMarkerClick(final Marker marker) {

                for (int i = 0; i < list.size(); i++) {
                    if (marker == markerMap.get("marke" + i) && list != null) {

                        mBaiduMap.hideInfoWindow();
                        Button button = new Button(getApplicationContext());
                        button.setBackgroundResource(R.drawable.bg_pop);
                        title = list.get(i).get("title").toString();
                        button.setText(title);
                        button.setTextColor(0x60000000);
                        button.getBackground().setAlpha(100);

                        button.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
//                                Intent intent1 = new Intent(POIListActivity.this,POIDetailActivity.class);
//                                startActivity(intent1);
                            }
                        });
                        LatLng pt = (LatLng) list.get(i).get("mLatLon");
                        InfoWindow mInfoWindow = new InfoWindow(button, pt, -100);
                        mBaiduMap.showInfoWindow(mInfoWindow);

                    }
                }

                return false;
            }
        });

        mBaiduMap.setOnMapClickListener(new BaiduMap.OnMapClickListener() {
            @Override
            public void onMapClick(LatLng latLng) {

                mBaiduMap.hideInfoWindow();

            }

            @Override
            public boolean onMapPoiClick(MapPoi mapPoi) {
                //在此处理低图标点击事件
                return false;
            }
        });


        option.setOpenGps(true);// 打开gps
        option.setCoorType("bd09ll"); // 设置坐标类型
        option.setScanSpan(1000);
//        option.setTimeOut(-1);
        mLocClient.setLocOption(option);
        mLocClient.start();
        mLocClient.requestLocation();

        btn_poilist_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isFirstLoc = true;
            }
        });
    }


    @Override
    protected void onResume() {
        super.onResume();
        mMapView.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mMapView.onPause();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
//        bitmap.recycle();
        // 退出时销毁定位
        mLocClient.stop();
        // 关闭定位图层
        mBaiduMap.setMyLocationEnabled(false);
        mMapView.onDestroy();
        mMapView = null;

    }

    public class MyLocationListenner implements BDLocationListener {

        @Override
        public void onReceiveLocation(BDLocation location) {
            // map view 销毁后不在处理新接收的位置
            if (location == null || mMapView == null)
                return;
            MyLocationData locData = new MyLocationData.Builder()
                    .accuracy(location.getRadius())
                            // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(100).latitude(location.getLatitude())
                    .longitude(location.getLongitude()).build();
            mBaiduMap.setMyLocationData(locData);
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(location.getLatitude(),
                        location.getLongitude());
                MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
                mBaiduMap.animateMapStatus(u);
            }
        }

        public void onReceivePoi(BDLocation poiLocation) {
        }
    }

    public class POIListAdapter extends BaseAdapter {
        private TextView textView_itempoilist_title;
        private TextView textView_itempoilist_address;
        private TextView textView_itempoilist_distance;

        @Override
        public int getCount() {
            return list.size();
        }

        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            final View view;
            if (convertView == null) {
                view = getLayoutInflater().inflate(R.layout.item_poilst, parent, false);
            } else {
                view = convertView;
            }
            textView_itempoilist_title = (TextView) view.findViewById(R.id.textView_itempoilist_title);
            textView_itempoilist_title.setText((String) list.get(position).get("title"));
            textView_itempoilist_address = (TextView) view.findViewById(R.id.textView_itempoilist_address);
            textView_itempoilist_address.setText((String) list.get(position).get("poi_street_address"));
            textView_itempoilist_distance = (TextView) view.findViewById(R.id.textView_itempoilist_distance);
            textView_itempoilist_distance.setText(list.get(position).get("distance") + "米");
            textView_itempoilist_title.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    //跳转到路径规划
                    if (list != null) {
                        Intent intent = new Intent(POIListActivity.this, POIDetailActivity.class);
                        Object endlat = list.get(position).get("gLat");
                        Object endlon = list.get(position).get("gLon");


                        String phone = (String) list.get(position).get("phone");
                        intent.putExtra("starlat", lat);
                        intent.putExtra("starlon", lon);
                        intent.putExtra("endlat", (Double) endlat);
                        intent.putExtra("endlon", (Double) endlon);
                        intent.putExtra("phone", phone);
                        startActivity(intent);
                    }

                }
            });


            return view;

        }
    }

    //选择范围
    public void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(POIListActivity.this);
        builder.setTitle("选择范围");
//        builder.setMessage("1000m内,\n2000m内，\n3000m内，\n4000m内，\n5000m内");
        final String[] str = new String[]{"1000m内", "2000m内", "3000m内", "4000m内", "5000m内"};
        builder.setItems(str, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                String scope = str[which];
                String ss = scope.substring(0, 4);
                range = Integer.decode(ss);
                getLocationData();
                TextView_m.setText(str[which]);
            }
        });
        builder.show();

    }


    //获取POI列表数据
    public void getLocationData() {
        final ProgressDialog progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("加载中……");
        AsyncTask<String, Integer, Integer> task = new AsyncTask<String, Integer, Integer>() {
            int error = 0;

            @Override
            protected Integer doInBackground(String... params) {

                LocationDataRequester locationDataRequester = new LocationDataRequester();
                try {
//微博接口获取数据
                    list = locationDataRequester.request(lat, lon, name, abc, range);

//根据经纬度扎点

                    for (int i = 0; i < 10; i++) {

                        BitmapDescriptor bitmap = BitmapDescriptorFactory
                                .fromResource(R.drawable.ic_loc_normal);
                        OverlayOptions ooA = new MarkerOptions()
                                .position((LatLng) list.get(i).get("mLatLon"))
                                .icon(bitmap)
                                .draggable(true);
                        Marker marke = (Marker) mBaiduMap.addOverlay(ooA);
                        markerMap.put("marke" + i, marke);

                    }
                    Log.d("title", list.get(0).get("title").toString());

                } catch (IOException e) {
                    error = 1;

                } catch (JSONException e) {
                    error = 2;
                }
                return error;
            }

            @Override
            protected void onPreExecute() {
                progressDialog.show();
                super.onPreExecute();
            }

            @Override
            protected void onPostExecute(Integer integer) {
                if (integer == 1) {
                    Toast.makeText(POIListActivity.this, "网络不稳定", Toast.LENGTH_SHORT).show();
                } else if (integer == 2) {
                    Toast.makeText(POIListActivity.this, " 服务器异常", Toast.LENGTH_SHORT).show();
                } else {
                    POIListAdapter pLadapter = new POIListAdapter();
                    listView_poiList.setAdapter(pLadapter);
                    progressDialog.dismiss();


                }
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                super.onProgressUpdate(values);
            }

        };
        task.execute();
    }

    public void getNextMarker() {
        Log.d("getNextMarker","getNextMarker");
        int listSize = list.size();
        int pageSize = 10;
        int page;
        int mor;
        int num = listSize % 10;
        if (num == 0) {
            page = listSize / pageSize;
        } else {
            page = (listSize / pageSize) + 1;
        }
        if (m > page){m=1;}
        if (m < 1){m = page;}
        if (m == page){
            mor = listSize;
        }else{
            mor = pageSize * m;
        }
        //隐藏marker
        mBaiduMap.clear();
        //需要显示的marker
        if (listSize >= page) {
            for (int i = pageSize * m - pageSize; i <mor ; i++) {
                
                BitmapDescriptor bitmap = BitmapDescriptorFactory
                        .fromResource(R.drawable.ic_loc_normal);
                OverlayOptions ooA = new MarkerOptions()
                        .position((LatLng) list.get(i).get("mLatLon"))
                        .icon(bitmap)
                        .draggable(true);
                Marker marke = (Marker) mBaiduMap.addOverlay(ooA);
                markerMap.put("marke" + i, marke);

            }


        }

    }
}
